package com.zhang.handle;

import com.alibaba.fastjson.JSON;
import com.zhang.async.EmailService;
import com.zhang.entity.ChannelBody;
import com.zhang.entity.ExecutionResults;
import com.zhang.entity.vo.NettyClientMessage;
import com.zhang.entity.vo.SendEmailBody;
import com.zhang.mapper.DeviceInfoMapper;
import com.zhang.mapper.ExecutionResultsMapper;
import com.zhang.mapper.UserInfoMapper;
import com.zhang.util.CommandRedisUtil;
import com.zhang.util.DeviceRedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Objects;

import static com.zhang.common.Constant.*;

/**
 * User: 张
 * Date: 2024-11-16
 * Time: 18:41
 * Description:
 */
@Component
public class NettyMessageHandle {
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private EmailService emailService;
    @Autowired
    private DeviceInfoMapper deviceInfoMapper;
    @Autowired
    private DeviceRedisUtil deviceRedisUtil;
    @Autowired
    private CommandRedisUtil commandRedisUtil;
    @Autowired
    private ExecutionResultsMapper executionResultsMapper;

    public void handleMessage(String message, String channelId) {
        ChannelBody channelBody = JSON.parseObject(message, ChannelBody.class);
        if (Objects.equals(channelBody.getModel(), DEVICE_INIT)) {
            // 将设备ip channel_id 保存到内存 中 ip为key channel_id为value
            deviceRedisUtil.addDevice(channelId, channelBody.getJsonStr());
        }
        if (Objects.equals(channelBody.getModel(), DEVICE_RESULT)) {
            //  对客户端返回的结构进行解析 获取操作模板id 操作id 返回参数 结果
            NettyClientMessage nettyClientMessage = JSON.parseObject(channelBody.getJsonStr(), NettyClientMessage.class);
            // todo 将redis的任务id擦除
            commandRedisUtil.removeCommandByExecuteId(nettyClientMessage.getExecutionId());
            // todo 记录执行结果
            executionResultsMapper.updateExecutionResults(
                    new ExecutionResults()
                            .setChannelId(channelId)
                            .setResultCode(nettyClientMessage.getCode())
                            .setExecutionResult(nettyClientMessage.getMessage())
            );
        }

    }

    public void handleExceptionMessage(String channelId) {
        String emailMessage = "设备 :" + deviceInfoMapper.getDeviceInfoByIp(deviceRedisUtil.getIp(channelId)).getDeviceName() + " ip:" + deviceRedisUtil.getIp(channelId) + " " + "异常下线";
        emailService.sendEmail(new SendEmailBody(userInfoMapper.getAdminUserEmail(), ALARM_EMAIL_TITLE, emailMessage));
        handleChannelInactive(channelId);
    }

    public void handleChannelInactive(String channelId) {
        deviceRedisUtil.removeDevice(channelId);
    }

}
